package com.app.bimo.mvp.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.app.bimo.R;
import com.app.bimo.commonbusiness.base.BaseActivity;
import com.app.bimo.commonbusiness.eventdata.ErrorGetUserInfo;
import com.app.bimo.commonbusiness.eventdata.FinishGetUserInfo;
import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.JumpPageUtil;
import com.app.bimo.commonbusiness.util.LoginService;
import com.app.bimo.commonbusiness.util.RouterHub;
import com.app.bimo.commonbusiness.util.RxBus;
import com.app.bimo.commonbusiness.util.RxLifecycleUtils;
import com.app.bimo.commonbusiness.util.SharedPreUtils;
import com.app.bimo.commonbusiness.util.WeakHandler;
import com.app.bimo.library_ad.TTAdManagerHolder;
import com.app.bimo.mvp.contract.SplashContract;
import com.app.bimo.mvp.model.model.SplashModel;
import com.app.bimo.mvp.presenter.SplashPresenter;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;

import androidx.annotation.MainThread;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import butterknife.BindView;

public class SplashActivity extends BaseActivity<SplashPresenter> implements WeakHandler.IHandler, SplashContract.View {

    @BindView(R.id.splash_container)
    private FrameLayout mSplashContainer;

    //广告相关
    private TTAdNative mTTAdNative;
    //开屏广告加载发生超时但是SDK没有及时回调结果的时候，做的一层保护。
    private final WeakHandler mHandler = new WeakHandler(this);
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 3000;
    //开屏广告是否已经加载
    private boolean mHasLoaded;

    //是否强制跳转到主页面
    private boolean mForceGoMain;

    private static final int MSG_GO_MAIN = 1;

    private String json;

    private BroadcastReceiver broadcastReceiver;




    @Override
    protected void initView() {

        mPresenter = new SplashPresenter(new SplashModel(),this);

        mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
        //在合适的时机申请权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题
        //在开屏时候申请不太合适，因为该页面倒计时结束或者请求超时会跳转，在该页面申请权限，体验不好
        // TTAdManagerHolder.getInstance(this).requestPermissionIfNecessary(this);
        //定时，AD_TIME_OUT时间到时执行，如果开屏广告没有加载则跳转到主页面
        mHandler.sendEmptyMessageDelayed(MSG_GO_MAIN, AD_TIME_OUT);
        initSetting();
        /**从本地存储中获取的地址**/
        json = SharedPreUtils.getInstance(SplashActivity.this).getString(Constant.APiUrl);
        if (DataUtil.isEmpty(json)) {
//            DownLoadUtils.getInstance().downloadBaseUrl(SplashActivity.this, BuildConfig.DOWNLOADURL, false);
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    goToMainActivity();
                }
            }
        };
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(broadcastReceiver, intentFilter);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected int setLayoutID() {
        return R.layout.activity_splash;
    }

    @Override
    public void handleMsg(Message msg) {
        goToMainActivity();
    }

    private void initSetting(){
        //MMKV进行数据迁移
        SharedPreUtils.getInstance(getApplicationContext()).changeData(getApplication());
        boolean isLogin = ((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).isLogin();
//        if (!isLogin) {
            ((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).devicesLogin(true);
//        }else{
//            //加载开屏广告
//            loadSplashAd();
//        }
        RxBus.getInstance().toObservable(RxLifecycleUtils.bindLifecycle(getLifecycle()), FinishGetUserInfo.class, t -> {
            SharedPreUtils.getInstance(getApplicationContext()).putBoolean(Constant.isDevicesLoginSucess, true);
            //加载开屏广告
            loadSplashAd();
        });
        RxBus.getInstance().toObservable(RxLifecycleUtils.bindLifecycle(getLifecycle()), ErrorGetUserInfo.class, t -> {
            SharedPreUtils.getInstance(getApplicationContext()).putBoolean(Constant.isDevicesLoginSucess, false);
            //加载开屏广告
            loadSplashAd();
        });

    }


    /**
     * 加载开屏广告
     */
    private void loadSplashAd() {
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId("887310359")
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920)
                .build();
        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            @MainThread
            public void onError(int code, String message) {
                mHasLoaded = true;
//                showToast(message);
                checkAndGotoMainActivity();

            }

            @Override
            @MainThread
            public void onTimeout() {
                mHasLoaded = true;
//                showToast("开屏广告加载超时");
                checkAndGotoMainActivity();
            }

            @Override
            @MainThread
            public void onSplashAdLoad(TTSplashAd ad) {
                mHasLoaded = true;
                mHandler.removeCallbacksAndMessages(null);
                if (ad == null) {
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();
                if (view != null) {
                    mSplashContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕宽
                    mSplashContainer.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                    //ad.setNotAllowSdkCountdown();
                } else {
                    checkAndGotoMainActivity();
                }

                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
//                        showToast("开屏广告点击");
                    }

                    @Override
                    public void onAdShow(View view, int type) {
//                        showToast("开屏广告展示");
                    }

                    @Override
                    public void onAdSkip() {
//                        showToast("开屏广告跳过");
                        checkAndGotoMainActivity();

                    }

                    @Override
                    public void onAdTimeOver() {
//                        showToast("开屏广告倒计时结束");
                        checkAndGotoMainActivity();
                    }
                });
                if (ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    ad.setDownloadListener(new TTAppDownloadListener() {
                        boolean hasShow = false;

                        @Override
                        public void onIdle() {

                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                            if (!hasShow) {
//                                showToast("下载中...");
                                hasShow = true;
                            }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                            showToast("下载暂停...");

                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                            showToast("下载失败...");

                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {

                        }
                    });
                }
            }
        }, AD_TIME_OUT);

    }

    /**
     * 跳转到主页面
     */
    private void checkAndGotoMainActivity() {
        if (DataUtil.isEmpty(json)) {
//            DownLoadUtils.getInstance().downloadBaseUrl(SplashActivity.this, BuildConfig.DOWNLOADURL, true);
        } else {
            goToMainActivity();
        }
    }

    /**
     * 跳转到主页面
     */
    private void goToMainActivity() {
        JumpPageUtil.jumpActivity(this,MainActivity.class,true);
    }




}
